package util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @author 石小俊
 * @date 2023年11月06日 10:17
 */
public class MyBatisUtil {

    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> local;

    static {
        local = new ThreadLocal<>();
        try {
            factory = new SqlSessionFactoryBuilder()
                    .build(MyBatisUtil
                            .class
                            .getClassLoader()
                            .getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("MyBatisUtil初始化失败");
        }
    }

    public static SqlSession getSession() {
        // 从线程池中获取对应的持久化管理器
        SqlSession session = local.get();
        // 如果没有取到,说明尚未获取过
        if (session == null) {
            // 从解析结果中获取到对应的持久化管理器
            session = factory.openSession();
            // 将持久化管理器存放到线程池中
            local.set(session);
        }
        return session;
    }

    public static void close() {
        SqlSession session = local.get();
        if (session != null) {
            session.close();
            local.remove();
        }
    }

}
